package com.ABdolphin.forum.interceptor;

import com.ABdolphin.forum.common.AppConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${ABdolphin-forum.login.url}")
    private String defaultURL;
    /**
     * 前置处理
     * @return true:继续流程 <br/> false: 流程中断
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session!=null&&session.getAttribute(AppConfig.USER_SESSION)!=null){
            return true;
        }
        if(!defaultURL.startsWith("/")){
            defaultURL="/"+defaultURL;
        }
        //校验不通过,跳转到登录界面
        response.sendRedirect(defaultURL);
        return false;
    }
}
